package cn.taobaoke.restful.service;

import cn.taobaoke.restful.domain.GlobalConfig;
import cn.taobaoke.restful.domain.GlobalConfigRepository;
import cn.taobaoke.restful.domain.PIDEntity;
import cn.taobaoke.restful.util.Constants;
import cn.taobaoke.restful.util.GsonUtil;
import com.vdurmont.emoji.EmojiParser;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yangzuo
 * @since 2017-03-27
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GlobalConfigService {

    /**
     * 存储全局配置信息.
     * 格式为json, 存在更新, 不存在插入
     *
     * @param data
     * @return
     */
    public GlobalConfig storeConfig(final Map<String, Object> data, final Long domainId) {
        String jsonString = GsonUtil.getJsonString(data);
        val configOpt = globalConfigRepository.findByTypeAndDomainId(GlobalConfig.CONFIG_TYPE_DEFAULT, domainId);

        if (configOpt.isPresent()) {
            val config = configOpt.get();
            config.setGlobalConfig(jsonString);
            return globalConfigRepository.save(config);
        }

        val config = new GlobalConfig();
        config.setType(GlobalConfig.CONFIG_TYPE_DEFAULT);
        config.setGlobalConfig(jsonString);
        config.setDomainId(domainId);
        return globalConfigRepository.save(config);
    }

    /**
     * @return
     */
    public Map<String, Object> queryConfig(final Long domainId) {
        val configOpt = globalConfigRepository.findByTypeAndDomainId(GlobalConfig.CONFIG_TYPE_DEFAULT, domainId);
        Map<String, Object> map = null;
        if (! configOpt.isPresent()) {
            map = GlobalConfig.DEFAULT_MAP;
        } else {
            String jsonString = configOpt.get().getGlobalConfig();
            if (jsonString != null) {
                map = GsonUtil.getObject(jsonString);
            }
            if (map == null) {
                map = GlobalConfig.DEFAULT_MAP;
            }
        }
        String oldPid = (String) map.get(Constants.ADMIN_PID);
        if (oldPid == null || oldPid.trim().isEmpty() || GlobalConfig.TJ_PID.equals(oldPid)) {
            // 说明没有进行分配系统PID, 则进行分配
            try {
                PIDEntity pidEntity = pidService.getFirstAvailablePID(domainId);
                if (pidEntity != null) {
                    map.put(Constants.ADMIN_PID, pidEntity.getPid());
                    storeConfig(map, domainId);

                    pidEntity.setIsAssigned(true);
                    pidService.updatePID(pidEntity);
                }
            } catch (Exception e) {
                map.put(Constants.ADMIN_PID, GlobalConfig.TJ_PID);
            }
        }

        String template = (String) map.get(Constants.SEND_PRODUCT_TEMPLATE);
        if (template == null || template.trim().isEmpty()) {
            template = Constants.PRODUCT_DEFAULT_TEMPLATE;
            map.put(Constants.SEND_PRODUCT_TEMPLATE, template);
        }
        // parse emoji to unicode
        template = EmojiParser.parseToUnicode(template);
        map.put(Constants.SEND_PRODUCT_TEMPLATE, template);

        return map;
    }

    public GlobalConfig getConfig(final Long domainId) {
        val configOpt = globalConfigRepository.findByTypeAndDomainId(GlobalConfig.CONFIG_TYPE_DEFAULT, domainId);
        return configOpt.orElse(null);
    }

    private final @NonNull PIDService pidService;

    private final @NonNull GlobalConfigRepository globalConfigRepository;
}
